package com.m1905.lib.download.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


import com.m1905.lib.download.model.DownloadDBItem;
import com.m1905.lib.download.util.DLog;
import com.m1905.lib.download.util.DownloadPreferences;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wanghao
 * @date 2022/8/11.
 * @des
 */
public class DBManager {

    private static final DBHelper mHelper = new DBHelper(DownloadPreferences.getAppContext());

    public static List<DownloadDBItem> queryAll() {
        List<DownloadDBItem> list = new ArrayList<>();
        SQLiteDatabase db = mHelper.getReadableDatabase();
        if (db != null && db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + DBHelper.TABLE_NAME, null);
            if (cursor != null) {
                int indexID = cursor.getColumnIndex(DBHelper.COLUMN_ID);
                int indexUrl = cursor.getColumnIndex(DBHelper.COLUMN_URL);
                int indexTitle = cursor.getColumnIndex(DBHelper.COLUMN_TITLE);
                int indexContentId = cursor.getColumnIndex(DBHelper.COLUMN_CONTENT_ID);
                int indexEpisodeId = cursor.getColumnIndex(DBHelper.COLUMN_EPISODE_ID);
                int indexEpisode = cursor.getColumnIndex(DBHelper.COLUMN_EPISODE);
                int indexIsVip = cursor.getColumnIndex(DBHelper.COLUMN_IS_VIP);
                int indexDownloadId = cursor.getColumnIndex(DBHelper.COLUMN_DOWNLOAD_ID);
                int indexDownloadType = cursor.getColumnIndex(DBHelper.COLUMN_DOWNLOAD_TYPE);
                int indexType = cursor.getColumnIndex(DBHelper.COLUMN_TYPE);
                int indexDefinition = cursor.getColumnIndex(DBHelper.COLUMN_DEFINITION);
                int indexBMonth = cursor.getColumnIndex(DBHelper.COLUMN_BMONTH);
                int indexUrlRouter = cursor.getColumnIndex(DBHelper.COLUMN_URL_ROUTER);
                int indexIMG = cursor.getColumnIndex(DBHelper.COLUMN_IMG);
                int indexPath = cursor.getColumnIndex(DBHelper.COLUMN_PATH);
                int indexResume = cursor.getColumnIndex(DBHelper.COLUMN_RESUME);
                int indexState = cursor.getColumnIndex(DBHelper.COLUMN_STATE);
                int indexTotalSize = cursor.getColumnIndex(DBHelper.COLUMN_TOTAL_SIZE);
                int indexDownloadSize = cursor.getColumnIndex(DBHelper.COLUMN_DOWNLOAD_SIZE);
                int indexDownloadSpeed = cursor.getColumnIndex(DBHelper.COLUMN_DOWNLOAD_SPEED);
                int indexErrorCode = cursor.getColumnIndex(DBHelper.COLUMN_ERROR_CODE);
                int indexErrorMsg = cursor.getColumnIndex(DBHelper.COLUMN_ERROR_MSG);
                while (cursor.moveToNext()) {
                    DownloadDBItem item = new DownloadDBItem();
                    item.setId(cursor.getInt(indexID));
                    item.setUrl(cursor.getString(indexUrl));
                    item.setTitle(cursor.getString(indexTitle));
                    item.setContentId(cursor.getString(indexContentId));
                    item.setEpisodeId(cursor.getString(indexEpisodeId));
                    item.setEpisode(cursor.getString(indexEpisode));
                    item.setIsVip(cursor.getInt(indexIsVip));
                    item.setDownloadId(cursor.getString(indexDownloadId));
                    item.setDownloadType(cursor.getInt(indexDownloadType));
                    item.setType(cursor.getInt(indexType));
                    item.setDefinition(cursor.getInt(indexDefinition));
                    item.setBmonth(cursor.getInt(indexBMonth));
                    item.setUrlRouter(cursor.getString(indexUrlRouter));
                    item.setImg(cursor.getString(indexIMG));
                    item.setPath(cursor.getString(indexPath));
                    item.setResume(cursor.getInt(indexResume) == 1);
                    item.setState(cursor.getInt(indexState));
                    item.setTotalSize(cursor.getLong(indexTotalSize));
                    item.setDownloadSize(cursor.getLong(indexDownloadSize));
                    item.setDownloadSpeed(cursor.getLong(indexDownloadSpeed));
                    item.setErrorCode(cursor.getInt(indexErrorCode));
                    item.setErrorMsg(cursor.getString(indexErrorMsg));
                    list.add(item);
                }

            }
            if (cursor != null) {
                cursor.close();
            }
        }
        return list;
    }


    public static long insertToDatabase(DownloadDBItem downloadItem) {
        long id = -1;
        SQLiteDatabase db = mHelper.getWritableDatabase();
        if (db != null && db.isOpen() && downloadItem != null) {
            ContentValues values = new ContentValues();
            long time = System.currentTimeMillis();
            values.put(DBHelper.COLUMN_TITLE, getString(downloadItem.getTitle(), ""));
            values.put(DBHelper.COLUMN_CONTENT_ID, getString(downloadItem.getContentId(), ""));
            values.put(DBHelper.COLUMN_EPISODE_ID, getString(downloadItem.getEpisodeId(), ""));
            values.put(DBHelper.COLUMN_EPISODE, getString(downloadItem.getEpisode(), ""));
            values.put(DBHelper.COLUMN_URL, getString(downloadItem.getUrl(), ""));
            values.put(DBHelper.COLUMN_IS_VIP, downloadItem.getIsVip());
            values.put(DBHelper.COLUMN_DOWNLOAD_ID, getString(downloadItem.getDownloadId(), ""));
            values.put(DBHelper.COLUMN_DOWNLOAD_TYPE, downloadItem.getDownloadType());
            values.put(DBHelper.COLUMN_DEFINITION, downloadItem.getDefinition());
            values.put(DBHelper.COLUMN_BMONTH, downloadItem.getBmonth());
            values.put(DBHelper.COLUMN_URL_ROUTER, getString(downloadItem.getUrlRouter(), ""));
            values.put(DBHelper.COLUMN_PATH, getString(downloadItem.getPath(), ""));
            values.put(DBHelper.COLUMN_RESUME, downloadItem.isResume() ? 1 : 0);
            values.put(DBHelper.COLUMN_IMG, getString(downloadItem.getImg(), ""));
            values.put(DBHelper.COLUMN_TYPE, downloadItem.getType());
            values.put(DBHelper.COLUMN_WATCH_TIME, time);
            values.put(DBHelper.COLUMN_CREATE_TIME, time);
            id = db.insert(DBHelper.TABLE_NAME, null, values);
            DLog.e("DBManager insertToDatabase: " + id);
        }
        return id;
    }


    public static boolean insertToDatabase(List<DownloadDBItem> downloadItems) {
        boolean result = false;
        SQLiteDatabase db = mHelper.getWritableDatabase();
        if (db != null && db.isOpen() && downloadItems != null && downloadItems.size() > 0) {
            try {
                db.beginTransaction();
                for (int i = 0; i < downloadItems.size(); i++) {
                    DownloadDBItem downloadItem = downloadItems.get(i);
                    ContentValues values = new ContentValues();
                    long time = System.currentTimeMillis();
                    values.put(DBHelper.COLUMN_TITLE, getString(downloadItem.getTitle(), ""));
                    values.put(DBHelper.COLUMN_CONTENT_ID, getString(downloadItem.getContentId(), ""));
                    values.put(DBHelper.COLUMN_EPISODE_ID, getString(downloadItem.getEpisodeId(), ""));
                    values.put(DBHelper.COLUMN_EPISODE, getString(downloadItem.getEpisode(), ""));
                    values.put(DBHelper.COLUMN_URL, getString(downloadItem.getUrl(), ""));
                    values.put(DBHelper.COLUMN_IS_VIP, downloadItem.getIsVip());
                    values.put(DBHelper.COLUMN_DOWNLOAD_ID, getString(downloadItem.getDownloadId(), ""));
                    values.put(DBHelper.COLUMN_DOWNLOAD_TYPE, downloadItem.getDownloadType());
                    values.put(DBHelper.COLUMN_DEFINITION, downloadItem.getDefinition());
                    values.put(DBHelper.COLUMN_BMONTH, downloadItem.getBmonth());
                    values.put(DBHelper.COLUMN_URL_ROUTER, getString(downloadItem.getUrlRouter(), ""));
                    values.put(DBHelper.COLUMN_PATH, getString(downloadItem.getPath(), ""));
                    values.put(DBHelper.COLUMN_RESUME, downloadItem.isResume() ? 1 : 0);
                    values.put(DBHelper.COLUMN_IMG, getString(downloadItem.getImg(), ""));
                    values.put(DBHelper.COLUMN_TYPE, downloadItem.getType());

                    values.put(DBHelper.COLUMN_TOTAL_SIZE, downloadItem.getTotalSize());
                    values.put(DBHelper.COLUMN_DOWNLOAD_SIZE, downloadItem.getDownloadSize());
                    values.put(DBHelper.COLUMN_DOWNLOAD_SPEED, downloadItem.getDownloadSpeed());
                    values.put(DBHelper.COLUMN_ERROR_CODE, downloadItem.getErrorCode());
                    values.put(DBHelper.COLUMN_ERROR_MSG, getString(downloadItem.getErrorMsg(), ""));
                    values.put(DBHelper.COLUMN_STATE, downloadItem.getState());

                    values.put(DBHelper.COLUMN_WATCH_TIME, time);
                    values.put(DBHelper.COLUMN_CREATE_TIME, time);
                    long id = db.insert(DBHelper.TABLE_NAME, null, values);
                    DLog.e("DBManager insertToDatabase: " + id);
                }
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                db.setTransactionSuccessful();
                db.endTransaction();
            }

        }
        return result;
    }

    public static void deleteDatabase(DownloadDBItem downloadItem) {
        SQLiteDatabase db = mHelper.getWritableDatabase();
        if (db != null && db.isOpen() && downloadItem != null && downloadItem.getId() > 0) {
            int id = db.delete(DBHelper.TABLE_NAME, DBHelper.COLUMN_ID + "=?", new String[]{String.valueOf(downloadItem.getId())});
            DLog.e("DBManager deleteDatabase: " + id);
        }
    }

    public static void deleteDatabase(List<DownloadDBItem> list) {
        SQLiteDatabase db = mHelper.getWritableDatabase();
        if (db != null && db.isOpen() && list != null && list.size() > 0) {
            db.beginTransaction();
            for (int i = 0; i < list.size(); i++) {
                db.delete(DBHelper.TABLE_NAME, DBHelper.COLUMN_ID + "=?", new String[]{String.valueOf(list.get(i).getId())});
            }
            db.setTransactionSuccessful();
            db.endTransaction();
        }
    }

    public static int updateStateToDatabase(DownloadDBItem downloadItem) {
        int id = -1;
        SQLiteDatabase db = mHelper.getWritableDatabase();
        if (db != null && db.isOpen() && downloadItem != null && downloadItem.getId() > 0) {
            ContentValues values = new ContentValues();
            values.put(DBHelper.COLUMN_STATE, downloadItem.getState());
            values.put(DBHelper.COLUMN_ERROR_CODE, downloadItem.getErrorCode());
            values.put(DBHelper.COLUMN_ERROR_MSG, downloadItem.getErrorMsg());
            values.put(DBHelper.COLUMN_DOWNLOAD_SPEED, downloadItem.getDownloadSpeed());
            id = db.update(DBHelper.TABLE_NAME, values, DBHelper.COLUMN_ID + "=?", new String[]{String.valueOf(downloadItem.getId())});
            DLog.e("DBManager updateStateToDatabase: " + id);
        }
        return id;
    }

    public static void updateProgressToDatabase(DownloadDBItem downloadItem) {
        SQLiteDatabase db = mHelper.getWritableDatabase();
        if (db != null && db.isOpen() && downloadItem != null && downloadItem.getId() > 0) {
            ContentValues values = new ContentValues();
            values.put(DBHelper.COLUMN_TOTAL_SIZE, downloadItem.getTotalSize());
            values.put(DBHelper.COLUMN_DOWNLOAD_SIZE, downloadItem.getDownloadSize());
            values.put(DBHelper.COLUMN_DOWNLOAD_SPEED, downloadItem.getDownloadSpeed());
            db.update(DBHelper.TABLE_NAME, values, DBHelper.COLUMN_ID + "=?", new String[]{String.valueOf(downloadItem.getId())});
        }
    }

    public static class DBHelper extends SQLiteOpenHelper {

        private static final String DB_NAME = "1905download.db";
        private static final int DB_VERSION = 1;
        private static final String TABLE_NAME = "download";

        private static final String COLUMN_ID = "id";
        private static final String COLUMN_TITLE = "title";
        private static final String COLUMN_CONTENT_ID = "content_id";
        private static final String COLUMN_EPISODE_ID = "episode_id";
        private static final String COLUMN_EPISODE = "episode";
        private static final String COLUMN_URL = "url";
        private static final String COLUMN_IS_VIP = "is_vip";
        private static final String COLUMN_DOWNLOAD_TYPE = "download_type";
        private static final String COLUMN_DOWNLOAD_ID = "download_id";
        private static final String COLUMN_TYPE = "type";
        private static final String COLUMN_DEFINITION = "definition";
        private static final String COLUMN_BMONTH = "bmonth";
        private static final String COLUMN_URL_ROUTER = "url_router";
        private static final String COLUMN_IMG = "img";
        private static final String COLUMN_PATH = "path";
        private static final String COLUMN_RESUME = "resume";
        private static final String COLUMN_STATE = "state";
        private static final String COLUMN_TOTAL_SIZE = "total_size";
        private static final String COLUMN_DOWNLOAD_SIZE = "download_size";
        private static final String COLUMN_DOWNLOAD_SPEED = "download_speed";
        private static final String COLUMN_ERROR_CODE = "error_code";
        private static final String COLUMN_ERROR_MSG = "error_msg";
        private static final String COLUMN_WATCH_TIME = "watch_time";
        private static final String COLUMN_CREATE_TIME = "create_time";

        public DBHelper(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            onUpgrade(db, 1, 1);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            for (int version = oldVersion; version <= newVersion; version++) {
                switch (version) {
                    case 1:
                        version1(db);
                        break;
                }
            }
        }

        public void version1(SQLiteDatabase database) {
            database.execSQL("CREATE TABLE " + TABLE_NAME + "("
                    + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + COLUMN_TITLE + " TEXT, "
                    + COLUMN_CONTENT_ID + " TEXT, "
                    + COLUMN_EPISODE_ID + " TEXT, "
                    + COLUMN_EPISODE + " TEXT, "
                    + COLUMN_URL + " TEXT, "
                    + COLUMN_IS_VIP + " INTEGER DEFAULT 0, "
                    + COLUMN_DOWNLOAD_TYPE + " INTEGER DEFAULT 0, "
                    + COLUMN_DOWNLOAD_ID + " TEXT, "
                    + COLUMN_TYPE + " INTEGER DEFAULT 0, "
                    + COLUMN_DEFINITION + " INTEGER DEFAULT 0, "
                    + COLUMN_BMONTH + " INTEGER DEFAULT 0, "
                    + COLUMN_URL_ROUTER + " TEXT, "
                    + COLUMN_IMG + " TEXT, "
                    + COLUMN_PATH + " TEXT, "
                    + COLUMN_RESUME + " INTEGER DEFAULT 0, "
                    + COLUMN_STATE + " INTEGER DEFAULT 0, "
                    + COLUMN_TOTAL_SIZE + " BIGINT DEFAULT 0, "
                    + COLUMN_DOWNLOAD_SIZE + " BIGINT DEFAULT 0, "
                    + COLUMN_DOWNLOAD_SPEED + " BIGINT DEFAULT 0, "
                    + COLUMN_ERROR_CODE + " INTEGER DEFAULT 0, "
                    + COLUMN_ERROR_MSG + " TEXT, "
                    + COLUMN_WATCH_TIME + " BIGINT DEFAULT 0, "
                    + COLUMN_CREATE_TIME + " BIGINT DEFAULT 0"
                    + ")");
        }

    }

    private static String getString(String str, String defString) {
        if (str == null) {
            return defString;
        }
        return str;
    }
}
